package com.pangolin.pangolinim.ui.base;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.appbar.AppBarLayout;
import com.jaeger.library.StatusBarUtil;
import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.R;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.app.mainApp;
import com.pangolin.pangolinim.service.CoreService;
import com.pangolin.pangolinim.ui.activity.SessionActivity;
import com.pangolin.pangolinim.ui.activity.SettingActivity;
import com.pangolin.pangolinim.ui.activity.UserInfoActivity;
import com.pangolin.pangolinim.ui.activity.WebViewActivity;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.GsonUtil;
import com.pangolin.pangolinim.utils.NotifyUtil;
import com.pangolin.pangolinim.utils.SPUtil;
import com.pangolin.pangolinim.utils.UIUtil;
import com.pangolin.pangolinim.widget.CustomDialog;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.Map;

import me.drakeet.materialdialog.MaterialDialog;

public abstract class BaseActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private UIMsgReceiver receiver = new UIMsgReceiver();

    private CustomDialog mDialogWaiting;
    private MaterialDialog mMaterialDialog;

    protected AppBarLayout mAppBar;
    protected FrameLayout mToolbar;
    public ImageView mToolbarNavigation;
    public AutoLinearLayout mLlToolbarTitle;
    public View mToolbarDivision;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //初始化函数（虚函数）
        init();

        //activity管理类
        ActivityCollector.addActivity(this);

        //子类不再需要设置布局ID
        setContentView(provideContentViewId());

        //设置标题栏
        setupAppBarAndToolbar();

        //沉浸式状态栏
        StatusBarUtil.setColor(this, UIUtil.getColor(R.color.colorPrimaryDark), 10);

        //view初始化函数（虚函数）
        initView();

        //控件事件监听函数（虚函数）
        initListener();
    }

    /**
     * setupAppBarAndToolbar函数
     * 设置AppBar和Toolbar
     */
    private void setupAppBarAndToolbar() {
        mAppBar = (AppBarLayout)findViewById(R.id.appBar);
        mToolbarNavigation = (ImageView)findViewById(R.id.ivToolbarNavigation);
        mToolbarDivision = (View)findViewById(R.id.vToolbarDivision);
        mLlToolbarTitle = (AutoLinearLayout)findViewById(R.id.llToolbarTitle);
        mToolbar = (FrameLayout) findViewById(R.id.flToolbar);
        //如果该应用运行在android 5.0以上设备，设置标题栏的z轴高度
        if (mAppBar != null && Build.VERSION.SDK_INT > 21) {
            mAppBar.setElevation(10.6f);
        }
        //隐藏标题栏
        if(getSupportActionBar() != null){
            getSupportActionBar().hide();
        }

        mToolbarNavigation.setVisibility(isToolbarCanBack() ? View.VISIBLE : View.GONE);
        mToolbarDivision.setVisibility(isToolbarCanBack() ? View.VISIBLE : View.GONE);
        mToolbarNavigation.setOnClickListener(v -> onBackPressed());
        mLlToolbarTitle.setPadding(isToolbarCanBack() ? 0 : 40, 0, 0, 0);
        mLlToolbarTitle.setGravity(isToolbarCenter() ? Gravity.CENTER : Gravity.LEFT);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册广播接收器
        intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastMsg.ACTIVITY_ACTION);
        receiver = new UIMsgReceiver();
        registerReceiver(receiver , intentFilter);
        Logger.d("UI registerReceiver");
    }

    @Override
    protected void onPause(){
        super.onPause();
        //注销广播接收器
        if(receiver != null){
            unregisterReceiver(receiver);
        }
        Logger.d("UI unregisterReceiver");
    }

    /**
     * 销毁所有activity，退出程序
     */
    protected void exitApp(){
        ActivityCollector.finishAll();
    }

    /**
     * 销毁除自身意外的所有activity
     */
    protected void closeOtherActivity(){
        ActivityCollector.finishAllExceptThis(this);
    }

    /**
     * 是否让Toolbar文字居中(默认不局中，一般一个应用中除了主界面，其他界面都是靠左对齐)
     */
    protected boolean isToolbarCenter() { return false; }

    /**
     * @ isToolbarCanBack函数
     * 是否让Toolbar有返回按钮(默认可以，一般一个应用中除了主界面，其他界面都是可以有返回按钮的)
     */
    protected boolean isToolbarCanBack() {
        return true;
    }

    /**
     * @ setToolbarTitle函数
     * 设置标题栏文字
     */
    protected void setToolbarTitle(String title) {
        TextView mToolbarTitle = (TextView)findViewById(R.id.tvToolbarTitle);
        mToolbarTitle.setText(title);
    }

    /**
     * @ init函数（抽象函数）
     * @TODO：activity子类必须继承实现该函数，用于完成初始化工作
     */
    protected abstract void init();

    /**
     * @ initView函数（抽象函数）
     * @TODO：activity子类必须继承实现该函数，用于完成view初始化工作
     */
    protected abstract void initView();

    /**
     * @ initListener函数（抽象函数）
     * @TODO：activity子类必须实现该抽象函数，用于完成各个控件的消息响应
     */
    protected abstract void initListener();

    /**
     * @ provideContentViewId函数（抽象函数）
     * @TODO：activity子类必须实现该抽象函数，用于获得activity布局
     */
    protected abstract int provideContentViewId();

    /**
     * @ CoreMessage函数（抽象函数）
     * @TODO：activity类必须实现该抽象函数，用于将服务的广播数据传给对应的activuty，并在子类中实现对应功能
     * @param bundleUtil 服务传送给UI的广播数据(bundleUtil包含消息类型，msg，和map格式的data)
     */
    protected abstract void CoreMessage(BundleUtil bundleUtil);

    /**
     * @ BroadcastSender函数
     * @TODO：广播发送函数，用于将消息发送给服务
     * @param bundle 要传送的数据封包，该封包使用BundleUtil组装
     */
    public void BroadcastSender(Bundle bundle){
        Intent intent = new Intent(BroadcastMsg.CORE_ACTION);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }

    /**
     * @ jumpToActivity函数
     * @TODO：跳转到activity
     * @param activity activity类
     */
    public void jumpToActivity(Class activity) {
        Intent intent = new Intent(this, activity);
        startActivity(intent);
    }

    /**
     * @ jumpToActivity函数
     * @TODO：跳转到activity
     * @param activity activity类
     * @param param1 要传递的参数
     */
    public void jumpToActivity(Class activity , String param1) {
        Intent intent = new Intent(this, activity);
        intent.putExtra("param1", param1);
        startActivity(intent);
    }

    /**
     * @ jumpToActivity函数
     * @TODO：跳转到activity
     * @param activity activity类
     * @param param1 要传递的参数
     * @param param2 要传递的参数
     */
    public void jumpToActivity(Class activity , String param1 , String param2) {
        Intent intent = new Intent(this, activity);
        intent.putExtra("param1", param1);
        intent.putExtra("param2", param2);
        startActivity(intent);
    }

    /**
     * @ showWaitingDialog函数
     * @TODO:显示等待提示框
     */
    public Dialog showWaitingDialog(String tip) {
        hideWaitingDialog();
        View view = View.inflate(this, R.layout.dialog_waiting, null);
        if (!TextUtils.isEmpty(tip))
            ((TextView) view.findViewById(R.id.tvTip)).setText(tip);
        mDialogWaiting = new CustomDialog(this, view, R.style.MyDialog);
        mDialogWaiting.show();
        mDialogWaiting.setCancelable(false);
        return mDialogWaiting;
    }

    /**
     * @hideWaitingDialog函数
     * @TODO:隐藏等待提示框
     */
    public void hideWaitingDialog() {
        if (mDialogWaiting != null) {
            mDialogWaiting.dismiss();
            mDialogWaiting = null;
        }
    }

    /**
     * @TODO:内嵌浏览器打开链接
     */
    public void jumpToWebViewActivity(String url) {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    /**
     * @TODO:启动service
     */
    public void startCoreService(){
        Intent startIntent = new Intent(this , CoreService.class);
        startService(startIntent);
    }

    /**
     * @TODO:停止service
     */
    public void stopCoreService(){
        Intent stopIntent = new Intent(this, CoreService.class);
        stopService(stopIntent);
    }

    /**
     * TODO:显示MaterialDialog
     */
    public MaterialDialog showMaterialDialog(String title, String message, String positiveText, String negativeText, View.OnClickListener positiveButtonClickListener, View.OnClickListener negativeButtonClickListener) {
        hideMaterialDialog();
        mMaterialDialog = new MaterialDialog(this);
        if (!TextUtils.isEmpty(title)) {
            mMaterialDialog.setTitle(title);
        }
        if (!TextUtils.isEmpty(message)) {
            mMaterialDialog.setMessage(message);
        }
        if (!TextUtils.isEmpty(positiveText)) {
            mMaterialDialog.setPositiveButton(positiveText, positiveButtonClickListener);
        }
        if (!TextUtils.isEmpty(negativeText)) {
            mMaterialDialog.setNegativeButton(negativeText, negativeButtonClickListener);
        }
        mMaterialDialog.show();
        return mMaterialDialog;
    }

    /**
     * TODO:隐藏MaterialDialog
     */
    public void hideMaterialDialog() {
        if (mMaterialDialog != null) {
            mMaterialDialog.dismiss();
            mMaterialDialog = null;
        }
    }

    public class UIMsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context , Intent intent){
            Bundle bundle = intent.getExtras();
            BundleUtil bundleUtil = new BundleUtil(bundle);
            Logger.d("UIMsgReceiver:type:%d" , bundleUtil.getType());
            Logger.d(bundleUtil.getData());
            switch (bundleUtil.getType()){
                case BroadcastMsg.SIG_CORE_SERVSTOPED:
                    //UIUtil.showToast("服务已结束");
                    break;
                case BroadcastMsg.SIG_CORE_CONNECT:
                    //UIUtil.showToast("服务器连接成功");
                    break;
                case BroadcastMsg.SIG_CORE_DISCONNECT:
                    UIUtil.showToast("服务器断开连接");
                    break;
                case BroadcastMsg.SIG_CORE_NETERR:
                    String errMsg = bundleUtil.getMsg() != null ? (String) bundleUtil.getMsg()  : "";
                    UIUtil.showToast("网络错误："+errMsg);
                    break;
                case BroadcastMsg.SIG_CORE_SYSERR:
                    errMsg = bundleUtil.getMsg() != null ? (String) bundleUtil.getMsg()  : "";
                    UIUtil.showToast("系统错误："+errMsg);
                    break;
                default:
            }
            //消息统一交给具体的Activity来处理
            CoreMessage(bundleUtil);
        }
    }
}